#pragma once

#include <iostream>
#include <vector>
#include <string>
#include <queue>

#include <pthread.h>

static const int defaultnum = 6;    // 默认先创建6个线程

struct ThreadInfo
{
    pthread_t tid;
    std::string name;
};

template<class T>
class ThreadPool
{
private:
    std::vector<ThreadInfo> threads_;   // 多个线程池（管理好多个线程）
    std::queue<T> task_queue_;          // 任务队列
    static ThreadPool<T> *tp_;          // 将线程池设计成为单例模式

    pthread_mutex_t lock_;  // 锁
    pthread_cond_t cond_;   // 操作锁的条件变量
private:
    ThreadPool(int num = defaultnum)
        :threads_(num)
    {
        pthread_mutex_init(&lock_, nullptr);
        pthread_cond_init(&cond_, nullptr);
    }
    ThreadPool(const ThreadPool &) = delete;
    const ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;
    ~ThreadPool()
    {
        pthread_mutex_destroy(&lock_);
        pthread_cond_destroy(&cond_);
    }

    // 加锁
    void Lock()
    {
        pthread_mutex_lock(&lock_);
    }
    // 解锁
    void Unlock()
    {
        pthread_mutex_unlock(&lock_);
    }
    // 线程等待
    void ThreadWait()
    {
        pthread_cond_wait(&cond_, &lock_);
    }
    // 唤醒线程
    void ThreadWakeUp()
    {
        pthread_cond_signal(&cond_);
    }
    // 判断任务队列是否为空
    bool IsQueueEmpty()
    {
        return task_queue_.empty();
    }
    // 获取线程的name
    std::string GetThreadName(pthread_t tid)
    {
        for(auto t1 : threads_)
        {
            if(t1.tid == tid) return t1.name;
        }
        return "None";
    }
    // 线程执行的任务
    static void *HandlerTask(void *args)
    {
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(args);
        std::string name = tp->GetThreadName(pthread_self());
        while (true)
        {
            tp->Lock();
            while(tp->IsQueueEmpty())
            {
                tp->ThreadWait();
            }
            T t = tp->Pop();
            tp->Unlock();

            t();
            printf("%s is running.....\n", name.c_str());
        }
        
    }
public:
    // 提供一个全局访问点
    static ThreadPool<T>* GetInstance()
    {
        if(tp_ == nullptr)
        {
            pthread_mutex_t mutex_ = PTHREAD_MUTEX_INITIALIZER;
            if(tp_ == nullptr){
                std::cout << "singleton create done first..." << std::endl;
                tp_ = new ThreadPool<T>();
            }
        }
        return tp_;
    }

    // 开始执行
    void Start()
    {
        int num = threads_.size();
        for(int i = 0; i < num; i++)
        {
            threads_[i].name = "thread-" + std::to_string(i+1);
            pthread_create(&(threads_[i].tid), nullptr, HandlerTask, this);
        }
    }

    // 来任务了，将任务放入任务队列中，并将线程唤醒
    void Push(const T &t)
    {
        Lock();
        task_queue_.push(t);
        ThreadWakeUp();
        Unlock();
    }

    // 开始做任务，从任务队列中拿出来任务，再执行任务
    T Pop()
    {
        T t = task_queue_.front();
        task_queue_.pop();
        return t;
    }   
};

template<class T>
ThreadPool<T> *ThreadPool<T>::tp_ = nullptr;